package com.example.hs.Controller;
import com.example.hs.Pojo.User;
import com.example.hs.Service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<User> register(@RequestBody User user) {
        return ResponseEntity.ok(userService.register(user));
    }

    @PostMapping("/login")
    public ResponseEntity<User> login(@RequestBody User user, HttpSession session) {
       if (user.getNum() != null && user.getPassword() != null) {
           return ResponseEntity.ok(userService.login(user.getNum(), user.getPassword(), session));
       }
       return ResponseEntity.badRequest().build();
    }


    @GetMapping("/profile")
    public ResponseEntity<User> getProfile(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return ResponseEntity.ok(userService.getProfile(user.getUserId())); // 从Session中获取用户信息
    }

    @PutMapping("/update/{userId}")
    public User updateProfile(@PathVariable int userId, @RequestBody User updatedUser) {
        return userService.updateProfile(userId, updatedUser);
    }
    @PostMapping("/logout")
    public void logout(HttpSession session) {
        userService.logout(session);
    }
}
